/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.core.exception;

import com.inspur.edp.lcm.metadata.api.entity.uri.AbstractURI;
import com.inspur.edp.lcm.metadata.api.entity.uri.MetadataURI;
import com.inspur.edp.lcm.metadata.api.exception.MetadataExceptionCode;
import com.inspur.edp.lcm.metadata.api.exception.MetadataNotFoundException;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class MetadataExceptionHandler {

    public static void handleMetadataNotFoundException(MetadataURI targetURI, AbstractURI sourceURI) {
        throw new MetadataNotFoundException("Lcm", MetadataExceptionCode.METADATA_NOT_FOUND, handleMetadataNotFoundMsg(targetURI, sourceURI), null, targetURI, sourceURI, null);
    }

    public static String handleMetadataNotFoundMsg(MetadataURI targetURI, AbstractURI sourceURI) {
        StringBuilder sb = new StringBuilder("未加载到元数据\"");
        if (!StringUtils.hasLength(targetURI.getCode()) || !StringUtils.hasLength(targetURI.getNameSpace()) || !StringUtils.hasLength(targetURI.getType())) {
            try {
                CustomizationService customizationService = SpringBeanUtils.getBean(CustomizationService.class);
                MetadataURI refMetadataURI = customizationService.getRefMetadataURI(targetURI.getId());
                if (refMetadataURI != null) {
                    targetURI = refMetadataURI;
                }
            } catch (Exception e) {
                log.error("从依赖关系中获取元数据的信息异常：{}", targetURI.getId(), e);
            }
        }
        sb.append(targetURI.getURIDesc());
        sb.append("\"，");
        if (sourceURI != null) {
            sb.append("<br>使用方式\"");
            sb.append(sourceURI.getURIDesc());
            sb.append("\"，");
        }

        sb.append("<br>请参考线上<a href='https://igix.inspures.com/app/cms/web/qa/home/pindex.html?#/Contents/614d0ca6-cb62-4d88-9ddd-1cbc853c38ff' target='blank'>解决方案</a>。");
        return sb.toString();
    }
}
